package com.tbit.uqbike.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.common.entity.RidePayLog;
import com.tbit.uqbike.client.constant.AccountConfigExtConstant;
import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 11:38 2022/11/16
 */
@Slf4j
@Service
public class FinishOrderServiceImpl implements FinishOrderService {
    @Autowired
    private MachineService machineService;
    @Autowired
    private UserService userService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private ParkService parkService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PayPointService payPointService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private RidePayLogService ridePayLogService;
    @Autowired
    private AdaPayService adaPayService;

    @Override
    public Integer finishOrder(Integer userId, Integer money, String remark, Integer dispatchType,

                               Integer type, Integer operatorId, String operatorName, String operatorPhone, Integer secondType) {
        log.info("结束订单,userId={},money={},remark={},dispatchType={},type={},operatorId={},operatorName={},operatorPhone={},secondType={}", userId, money, remark, dispatchType, type, operatorId, operatorName, operatorPhone, secondType);
        /**为2则是人工结束订单，3是超时结束订单*/
        /**订单信息**/
        User user = Optional.ofNullable(userService.getByUserId(userId))
                .orElseThrow(() -> new BaseException("-20005", "用户不存在"));
        /**订单信息**/
        RideLog rideLog = Optional.ofNullable(rideLogService.getByUserIdNotFinish(userId))
                .orElseThrow(() -> new BaseException("-3006", "骑行订单已经结束"));
        Park park = parkService.getByUserId(user.getUserId());
        String serNO = UUID.randomUUID().toString();
        Map<String, String> map = new HashMap<>();

        Double lessMoney = machineService.getMoney(user, rideLog, park, dispatchType, serNO, map, type, money,
                operatorId, operatorName, operatorPhone, secondType, AccountConfigExtConstant.ACCOUNTCONFIG_AFTERPAY_OPEN);
        /**需要充值金额大于0*/
        String brtInfo = redisService.get(serNO);
        BorrowReturnTer info = JSONObject.parseObject(brtInfo, BorrowReturnTer.class);
        if (lessMoney.intValue() > 0) {
            info.setLessMoney(lessMoney.intValue());
        }
        //分账金额
        Double cashMoney=info.getMoney()>=user.getMoney()?user.getMoney():info.getMoney();
        AccountConfig accountConfig = accountConfigService.getByAccountId(rideLog.getAccountId());
        Integer wxZffMm = Optional.ofNullable(accountConfig).map(o -> o.getWxZffMm()).orElseGet(() -> 0);
        if (wxZffMm == 1) {
            String remark1 = "骑行扣费";
            log.info("完结支付分订单，入参，user={},lessMoney={},serNO={},rideLog={}", user, lessMoney, serNO, rideLog);
            boolean zffResult = payPointService.finishOrderOut(user, lessMoney, serNO, rideLog.getAccountId(),

                    DateTimeUtil.getHourMinuteSecond(rideLog.getStartTime(), info.getEndTime()), info.getDispatchMoney() == null ? 0 :
                            info.getDispatchMoney().intValue(), remark1);
            /**支付分成功支付，直接结束，等回调*/
            log.info("完结支付分订单，返回，serNO={},zffResult={}", serNO, zffResult);
            if (zffResult) {
                return lessMoney.intValue();
            }
        }

        boolean isPay = false;
        List<RidePayLog> ridePayLogs = ridePayLogService.getByRideOrderNO(rideLog.getOrderNO());
        if (!ridePayLogs.isEmpty()) {
            for (RidePayLog ridePayLog : ridePayLogs) {
                if (System.currentTimeMillis() - ridePayLog.getUpdateTime().getTime() < 60 * 1000) {
                    isPay = true;
                }
            }
        }
        if (ridePayLogs.isEmpty() || !isPay) {
            redisService.add(RedisConstant.MACHINE_RETURN_LOCAL + info.getMachineNO(),
                    JSON.toJSONString(new Point(info.getLo(),info.getLa())), 60);
            if (type == 3) {
                info.setRemark(info.getRemark() + ",超时结束订单");
                machineService.cash(info);
            } else {
                ///人工结束订单金额为指定金额
                if (remark != null) {
                    info.setRemark(remark);
                }
                machineService.cash(info);
            }
            //人工结束订单金额足够支付也要触发余额分账
            if(lessMoney==0){
                log.info("结束订单记录区域,userId={},accountId={},orderNO={}",userId,rideLog.getAccountId(),rideLog.getOrderNO());
                adaPayService.delay(cashMoney,user,rideLog.getAccountId(),rideLog.getOrderNO(),info.getMoney().intValue());
            }
        } else {
            log.info("存在用户待支付充值，结束失败" + user.getUserId());
            throw new BaseException("-3072", "存在用户未结束充值,请稍等1分钟再试");
        }
        return lessMoney.intValue();
    }
}
